/*
 * lua_plug.c
 *
 *  Created on: 2012-2-28
 *      Author: lius
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

/* call a function `f' defined in Lua */
char *get_conf(lua_State *L)
{
	char *z;
	int a;
	printf("stack size[%d]\n", lua_gettop (L));
	lua_getglobal(L, "load_conf");
	printf("stack size[%d][%d]\n", lua_gettop (L), lua_isfunction(L, -1));

	if (lua_pcall(L, 0, 1, 0) != 0)
		printf("error running function `load_conf': %s\n", lua_tostring(L, -1));
	/* retrieve result */
	if (!lua_istable(L, -1))
		printf("function `get_cmd_list' must return a table\n");
	printf("stack size[%d][%d][%d]\n", lua_gettop (L), lua_isfunction(L, 1), lua_istable(L, 2));
	lua_getglobal(L, "__parse_ra_tbl");
	printf("stack size[%d][%d][%d]\n", lua_gettop (L), lua_isfunction(L, 1), lua_istable(L, 2));
	lua_pushvalue(L, 1);
	printf("stack size[%d][%d][%d]\n", lua_gettop (L), lua_isfunction(L, 1), lua_istable(L, 2));
	lua_remove(L, 1);
	printf("stack size[%d][%d][%d]\n", lua_gettop (L), lua_isfunction(L, 1), lua_istable(L, 2));
	if (lua_pcall(L, 1, 0, 0) != 0)
		printf("error running function `__parse_ra_tbl': %s\n", lua_tostring(L, -1));

	lua_pop(L, 1);
	if(z)
		return (strdup(z));
	else
		return NULL;
}


int __init__lua(int argc, char **argv)
{
	char *pfile = NULL;
	int red,green,blue;
	lua_State *L = luaL_newstate(); /* opens Lua */
	luaL_openlibs(L);

	if (2 != argc) {
		printf("please input a file\n");
		exit(1);
	}

	pfile = (char *)argv[1];

	if(luaL_loadfile(L, pfile) || lua_pcall(L, 0, 0, 0))
	{
		printf("cannot run configuration file: %s",
				lua_tostring(L, -1));
	}

	get_conf(L);
	lua_close(L);
	return 1;
}
